﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using GPSTracker.Helper;
using GPSTracker.Views.DAL;

namespace GPSTracker.Views.Delivery
{
    public partial class DispatchEntry : System.Web.UI.Page
    {
        private DispatchEntryDAL objDispatchEntryDAL = new DispatchEntryDAL();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                grdView.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;

                if (!IsPostBack)
                {
                    BindArea();
                    BindTempo();
                    BindDeliveryBoy();
                    cmbArea.Focus();
                }

            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "Page_Load");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void cmb_DataBound(object sender, EventArgs e)
        {
            var list = sender as ASPxComboBox;
            var lEi = new ListEditItem();
            lEi.Text = "--Select--";
            if (list != null)
            {
                list.Items.Insert(0, lEi);
            }
            list.SelectedIndex = 0;
        }

        public void BindArea()
        {
            try
            {
                var dt = new DataTable();
                dt = objDispatchEntryDAL.FillArea();
                if (dt.Rows.Count > 0)
                {
                    cmbArea.DataSource = dt;
                    cmbArea.TextField = "AreaName";
                    cmbArea.ValueField = "AreaID";
                    cmbArea.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "BindArea");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindTempo()
        {
            try
            {
                var dt = new DataTable();
                if (Session["LoginMaster"] != string.Empty && Session["LoginMaster"] != null)
                {
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;

                    dt = objDispatchEntryDAL.FillTempo(lg.BranchID.ToString(), lg.WarehouseID.ToString(), lg.LoginID.ToString());
                }
                if (dt.Rows.Count > 0)
                {
                    cmbTempo.DataSource = dt;
                    cmbTempo.TextField = "TempoNo";
                    cmbTempo.ValueField = "TempoID";
                    cmbTempo.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "BindTempo");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindDeliveryBoy()
        {
            try
            {
                var dt = new DataTable();
                if (Session["LoginMaster"] != string.Empty && Session["LoginMaster"] != null)
                {
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    dt = objDispatchEntryDAL.FillDeliveryBoy(lg.BranchID.ToString(), lg.WarehouseID.ToString(), lg.LoginID.ToString());
                }
                if (dt.Rows.Count > 0)
                {
                    cmbDeliveryBoy.DataSource = dt;
                    cmbDeliveryBoy.TextField = "EmpName";
                    cmbDeliveryBoy.ValueField = "LoginID";
                    cmbDeliveryBoy.DataBind();
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "BindDeliveryBoy");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbArea.Text != "--Select--" && cmbArea.Text != string.Empty)
                {
                    string strAbc = cmbArea.Value.ToString();
                }
                if (Session["LoginMaster"] != string.Empty && Session["LoginMaster"] != null)
                {
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    Session["WarehouseID"] = lg.WarehouseID;
                    Session["LoginID"] = lg.LoginID;

                    //SqlDataSource1.DataBind();
                    string strAreaID = string.Empty;
                    if (cmbArea.Text != "--Select--")
                    {
                        strAreaID = cmbArea.Value.ToString();
                    }
                    else
                    {
                        strAreaID = "0";
                    }
                    BindSqlDataSource(lg.LoginID.ToString(), lg.WarehouseID.ToString(), strAreaID);
                }
                else
                {
                    Session["WarehouseID"] = "0";
                    Session["LoginID"] = "0";
                    SqlDataSource1.DataBind();
                    BindSqlDataSource(string.Empty, string.Empty, string.Empty);
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "btnGo_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindSqlDataSource(string strLoginID, string strWarehouseID, string strAreaID)
        {
            try
            {
                SqlDataSource1.ConnectionString = CommonFx.GetSqlConStr();
                SqlDataSource1.SelectCommand = "EXEC dbo.SP_GetDeliveryForDispatch @pWhouseID = '" + strWarehouseID + "', @pLoginID = '" + strLoginID + "', @pAreaID = '" + strAreaID + "' ";
                SqlDataSource1.DataBind();
                grdView.DataBind();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "BindSqlDataSource");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void grdView_AfterPerformCallback(object sender, ASPxGridViewAfterPerformCallbackEventArgs e)
        {
            try
            {
                if (Session["LoginMaster"] != string.Empty && Session["LoginMaster"] != null)
                {
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    Session["WarehouseID"] = lg.WarehouseID;
                    Session["LoginID"] = lg.LoginID;

                    string strAreaID = string.Empty;
                    if (cmbArea.Text != "--Select--")
                    {
                        strAreaID = cmbArea.Value.ToString();
                    }
                    else
                    {
                        strAreaID = "0";
                    }

                    BindSqlDataSource(lg.LoginID.ToString(), lg.WarehouseID.ToString(), strAreaID);
                }
                else
                {
                    Session["WarehouseID"] = "0";
                    Session["LoginID"] = "0";
                    SqlDataSource1.DataBind();

                    BindSqlDataSource(string.Empty, string.Empty, string.Empty);
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "grdView_AfterPerformCallback");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void grdView_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "grdView_CustomButtonCallback");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnAssign_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "btnAssign_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }
        
        public void Save()
        {
            try
            {
                var settings = new XmlWriterSettings();
                settings.NewLineHandling = NewLineHandling.Entitize;
                settings.Indent = true;
                settings.OmitXmlDeclaration = true;

                var sb = new StringBuilder();

                var CmdSave = new SqlCommand();
                CmdSave.Connection = CommonFx.GetSqlCon();
                CmdSave.CommandType = CommandType.StoredProcedure;
                CmdSave.CommandText = "SP_UpdateDispatch";

                using (var xw = XmlWriter.Create(sb, settings))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("CS");

                    var fieldValues = grdView.GetSelectedFieldValues(new string[] { "DeliveryEntryID", "DeliveryEntryID" });
                    foreach (object[] item in fieldValues)
                    {
                        var strDeliveryEntryID = item[0].ToString();
                        var Name = item[1].ToString();

                        xw.WriteStartElement("Dispatch");
                        xw.WriteElementString("DeliveryEntryID", strDeliveryEntryID);
                        xw.WriteElementString("TempoID", cmbTempo.Value.ToString());
                        xw.WriteElementString("DeliveryBoyID", cmbDeliveryBoy.Value.ToString());
                        xw.WriteEndElement();
                    }

                    xw.WriteEndDocument();
                    xw.Close();
                }

                CmdSave.Parameters.Add(new SqlParameter("@pXML", sb.ToString()));
                var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                CmdSave.Parameters.Add(new SqlParameter("@pLoginID", lg.LoginID.ToString()));
                CmdSave.Parameters.Add("@pIsErrorFound", SqlDbType.Bit);
                CmdSave.Parameters.Add("@pErrorMessage", SqlDbType.NVarChar, 4000);

                CmdSave.Parameters["@pIsErrorFound"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pErrorMessage"].Direction = ParameterDirection.Output;
                CmdSave.ExecuteNonQuery();

                var str = CmdSave.Parameters["@pIsErrorFound"].Value.ToString();
                if (!Convert.ToBoolean(CmdSave.Parameters["@pIsErrorFound"].Value))
                {
                }

                grdView.FilterExpression = string.Empty;

                if (Session["LoginMaster"] != string.Empty && Session["LoginMaster"] != null)
                {
                    //var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    Session["WarehouseID"] = lg.WarehouseID;
                    Session["LoginID"] = lg.LoginID;

                    //SqlDataSource1.DataBind();
                    string strAreaID = string.Empty;
                    if (cmbArea.Text != "--Select--")
                    {
                        strAreaID = cmbArea.Value.ToString();
                    }
                    else
                    {
                        strAreaID = "0";
                    }

                    BindSqlDataSource(lg.LoginID.ToString(), lg.WarehouseID.ToString(), strAreaID);
                }
                else
                {
                    Session["WarehouseID"] = "0";
                    Session["LoginID"] = "0";
                    SqlDataSource1.DataBind();
                    BindSqlDataSource(string.Empty, string.Empty, string.Empty);
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Dispatch Entry", "Save");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void Assign()
        {
            var settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.Entitize;
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new StringBuilder();

            var CmdSave = new SqlCommand();
            CmdSave.Connection = CommonFx.GetSqlCon();
            CmdSave.CommandType = CommandType.StoredProcedure;
            CmdSave.CommandText = "SP_SetTempDispatch";

            using (var xw = XmlWriter.Create(sb, settings))
            {
                xw.WriteStartDocument();
                xw.WriteStartElement("CS");
                var fieldValues = grdView.GetSelectedFieldValues(new string[] { "DeliveryEntryID", "DeliveryEntryID" });
                foreach (object[] item in fieldValues)
                {
                    var strDeliveryEntryID = item[0].ToString();
                    var Name = item[1].ToString();

                    xw.WriteStartElement("TempDispatch");
                    xw.WriteElementString("DeliveryEntryID", strDeliveryEntryID);
                    xw.WriteElementString("TempoID", "1");
                    xw.WriteElementString("DeliveryBoyID", "1");
                    xw.WriteEndElement();
                }
                xw.WriteEndDocument();
                xw.Close();
            }
            CmdSave.Parameters.Add(new SqlParameter("@pXML", sb.ToString()));
            var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
            CmdSave.Parameters.Add(new SqlParameter("@pLoginID", lg.LoginID.ToString()));
            CmdSave.ExecuteNonQuery();
            grdView.DataBind();
        }

        //-- CODE END
    }
}
